/*
 * TMap Designer - A Thematic Map design software
 * Copyright (C) 2006 World Health Organization
 * http://www.who.int
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package who.tmap.ui.util;

import java.awt.Container;
import java.io.File;
import java.util.ArrayList;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import org.apache.log4j.Logger;

import who.tmap.bo.BizObject;
import who.tmap.bo.BizObjects;
import who.tmap.bo.MultiLayerThematicMap;
import who.tmap.bo.ThematicMap;
import who.tmap.bo.ThematicMapLayer;
import who.tmap.bo.impl.BizObjectFactory;
import who.tmap.common.TMapException;
import who.tmap.dao.MultiLayerThematicMapDAO;
import who.tmap.dao.TMapDAOException;
import who.tmap.dao.ThematicMapDAO;
import who.tmap.dao.impl.DAOFactory;
import who.tmap.toolkit.MultiLayerThematicMapToolKit;
import who.tmap.ui.JDialogImageOutputSize;
import who.tmap.ui.JFrameMultiLayerThematicMap;
import who.tmap.ui.undo.UndoManager;
import who.tmap.ui.undo.impl.UndoManagerImpl;

public class MultiLayerThematicMapUIHelper extends BaseUIHelper {

    private static Logger logger = Logger.getLogger(MultiLayerThematicMapUIHelper.class);
    
    private static UndoManager undoManager =UndoManagerImpl.getInstance();
    
    private static final DAOFactory daof =DAOFactory.getInstance();
    private MultiLayerThematicMapToolKit mltk;
    
    public MultiLayerThematicMapUIHelper() {
    	super();
    }
    
    public BizObject newMultiLayerThematicMap() throws TMapException {
    	BizObjectFactory bof =BizObjectFactory.getInstance();
    	MultiLayerThematicMap mltm =(MultiLayerThematicMap)bof.get( BizObjects.MULTI_LAYER_THEMATIC_MAP );
    	
    	return mltm;
    }
    
	public BizObject openMultiLayerThematicMap( Container container )  {
		MultiLayerThematicMap mltm =null;
		JFileChooser fileChooser =new JFileChooser();
		FileFilter mltFileFilter =new FileChooserFilter( FileChooserFilter.MULTI_LAYER_THEMATIC_MAP_EXT );
		fileChooser.addChoosableFileFilter( mltFileFilter );	
		FileFilter tmaFileFilter =new FileChooserFilter( FileChooserFilter.THEMATIC_MAP_EXT );
		fileChooser.addChoosableFileFilter( tmaFileFilter );
		FileFilter tmlFileFilter =new FileChooserFilter( FileChooserFilter.THEMATIC_MAP_LINKED_EXT );
		fileChooser.addChoosableFileFilter( tmlFileFilter );		

		fileChooser.setFileFilter( mltFileFilter );
		fileChooser.setCurrentDirectory( getTmaDir( container ) );
		
		// Open file dialog.
		int retVal =fileChooser.showOpenDialog(	container );
		
		if ( retVal == JFileChooser.APPROVE_OPTION ) {		
		
			File file =fileChooser.getSelectedFile();
			
			setTmaDir( file.getParentFile() );
			
			if ( fileChooser.getFileFilter().equals( tmaFileFilter ) 
					|| fileChooser.getFileFilter().equals( tmlFileFilter ) ) {
			
	        	try {
					mltm =(MultiLayerThematicMap)BizObjectFactory.getInstance().get( BizObjectFactory.MULTI_LAYER_THEMATIC_MAP );
		        	mltm.setLayers( new ArrayList<ThematicMapLayer>() );
		        	
		        	ThematicMapLayer layer =loadLayer( file );
			    	
			    	mltm.getLayers().add( layer );
			    	
				} catch (TMapException e) {
					miscUIHelper.displayErrorMessage( container, e );
				}

			
			} else {
				try {
			    	MultiLayerThematicMapDAO mltmDAO = (MultiLayerThematicMapDAO)daof.get( DAOFactory.MULTI_LAYER_THEMATIC_MAP );
			    	mltm =(MultiLayerThematicMap)mltmDAO.load( file.getAbsolutePath() );
			    	
				} catch( TMapException e1 ) {
					miscUIHelper.displayErrorMessage( container, e1 );
				}
			}
		    
		}
		
	    return mltm;
	}   
	
    private void save( MultiLayerThematicMap mltm ) throws TMapDAOException {
    	MultiLayerThematicMapDAO mltmDAO = (MultiLayerThematicMapDAO)daof.get( DAOFactory.MULTI_LAYER_THEMATIC_MAP );
    	    	
    	mltmDAO.save( mltm.getFile().getAbsolutePath(), mltm );
    	mltm.setDirty(false);
    }
    
	public File save( Container container, BizObject bizObject, int width, int height ) {
		MultiLayerThematicMap thematicMap =(MultiLayerThematicMap)bizObject;
		
		try {
	        if ( thematicMap.getFile() != null ) {
	            save( thematicMap );
	            return thematicMap.getFile();
	        } else {
	        	return saveAs( container, thematicMap, width, height );
	        }		
        } catch (TMapDAOException e) {
            miscUIHelper.displayErrorMessage( container, e );
        }        
        
        return null;
	}	
	
	public File saveAs( Container container, BizObject bizObject, int width, int height ) {
	    File file =null;
	    MultiLayerThematicMap mltm =(MultiLayerThematicMap)bizObject;
		JFileChooser fileChooser = new JFileChooser();
		
		FileChooserFilter jpgFcf =new FileChooserFilter( FileChooserFilter.JPG_EXT );
		FileChooserFilter pngFcf =new FileChooserFilter( FileChooserFilter.PNG_EXT );
		FileChooserFilter tmaFcf =new FileChooserFilter( FileChooserFilter.MULTI_LAYER_THEMATIC_MAP_EXT );	
		
		fileChooser.addChoosableFileFilter( jpgFcf );
		fileChooser.addChoosableFileFilter( tmaFcf );		
		fileChooser.addChoosableFileFilter( pngFcf );
	
		fileChooser.setFileFilter( tmaFcf );
		fileChooser.setCurrentDirectory( getTmaDir( container ) );
		fileChooser.setSelectedFile( new File( "*" + FileChooserFilter.MULTI_LAYER_THEMATIC_MAP_EXT ) );
		
		// Save file dialog.
		int retVal =fileChooser.showSaveDialog(container);
		
		if ( retVal == JFileChooser.APPROVE_OPTION ) {
			file =fileChooser.getSelectedFile();
			
			setTmaDir( fileChooser.getSelectedFile().getParentFile() );
	
		    logger.debug( "selectedFile=[" + file + "]" );

	        if ( file.exists() ) {

	            int n =JOptionPane.showConfirmDialog( container,
	                    "This file already exists. Do you want to erase it?",
	                    "Save Multi-Layer Thematic Map",
	                    JOptionPane.YES_NO_OPTION);
	            if ( n == JOptionPane.NO_OPTION ) {
	                file =null;
	            }
	        }
	        
	        if ( file != null ) {
	        	
	        	FileFilter fcf =fileChooser.getFileFilter();
	        	
	        	if ( fcf.equals( (FileFilter)tmaFcf )
	        			|| file.getAbsolutePath().endsWith( FileChooserFilter.MULTI_LAYER_THEMATIC_MAP_EXT ) ) {	        	
		        	mltm.setFile( file );
	            	try {            		
						save( mltm );

					} catch (TMapDAOException e) {
			            miscUIHelper.displayErrorMessage( container, e );
					}
	        	} else {
	        		try {
	        			JDialogImageOutputSize dlg =new JDialogImageOutputSize( null, width, height );
	        			dlg.setModal( true );
	        			dlg.getJCheckBoxRemoveBlankEdges().setVisible( false );
	        			dlg.setVisible( true );
	        			
	        			int imgWidth =dlg.getImgWidth();
	        			int imgHeight =dlg.getImgHeight();
	        			boolean okPressed =dlg.isOkPressed();
	        			//boolean removeBlankEdges =dlg.isRemoveBlankEdges();
	        			
	        			dlg.dispose();
	        			
	        			if ( okPressed ) {
	        				boolean success =mltk.saveThematicMapAsBitmap( file, ((FileChooserFilter)fcf).getExtension()
	        											, imgWidth, imgHeight );
	        			}
	        			
					} catch (Exception e) {
			            miscUIHelper.displayErrorMessage( container, e );
					}
					
					file =null;
	        	}
	        }

		}
		
		return file;
	}	
	
	public BizObject newThematicMapLayer() {
		BizObjectFactory bof =BizObjectFactory.getInstance();
		ThematicMapLayer layer =null;
		try {
			layer = (ThematicMapLayer)bof.get( BizObjects.THEMATIC_MAP_LAYER );
		} catch (TMapException e) {
			e.printStackTrace();
		}
		
		return layer;
	}
    
	public BizObject openThematicMap( Container container )  {
		ThematicMapLayer layer =null;
		JFileChooser fileChooser = new JFileChooser();
		FileFilter tmaFileFilter =new FileChooserFilter( FileChooserFilter.THEMATIC_MAP_EXT );
		fileChooser.addChoosableFileFilter( tmaFileFilter );		
		fileChooser.addChoosableFileFilter( new FileChooserFilter( FileChooserFilter.THEMATIC_MAP_LINKED_EXT ) );		

		fileChooser.setFileFilter( tmaFileFilter );
		fileChooser.setCurrentDirectory( getTmaDir( container ) );
		
		// Open file dialog.
		int retVal =fileChooser.showOpenDialog(	container );
		
		if ( retVal == JFileChooser.APPROVE_OPTION ) {		
		
			File file =fileChooser.getSelectedFile();
			
			setTmaDir( file.getParentFile() );
			
			try {				
				layer =loadLayer( file );
		    	
			} catch( TMapException e1 ) {
				miscUIHelper.displayErrorMessage( container, e1 );
			}
		    
		}
		
	    return layer;
	}     
	
	public ThematicMapLayer loadLayer( File file ) throws TMapException {
    	ThematicMapDAO thematicMapDAO = (ThematicMapDAO)daof.get( DAOFactory.THEMATIC_MAP );
    	ThematicMap thematicMap =(ThematicMap)thematicMapDAO.load( file.getAbsolutePath() );
    	
    	BizObjectFactory bof =BizObjectFactory.getInstance();
    	ThematicMapLayer layer =(ThematicMapLayer)bof.get( BizObjects.THEMATIC_MAP_LAYER );
    	
    	layer.setThematicMap( thematicMap );
    	layer.setFile( file );
    	layer.setName( file.getName() );
    	
    	return layer;
	}
	
	public ThematicMapLayer duplicateLayer( ThematicMapLayer srcLayer, String tgtLayerName ) throws TMapException {
    	ThematicMapDAO thematicMapDAO = (ThematicMapDAO)daof.get( DAOFactory.THEMATIC_MAP );
    	
    	File tmpFile =new File( getTmaDir( null ) + "/tmp.tma" );
    	
    	thematicMapDAO.save( tmpFile.getAbsolutePath(), srcLayer.getThematicMap() );
    	
    	ThematicMapLayer layer =loadLayer( tmpFile );
    	layer.setFile( new File( srcLayer.getThematicMap().getFile().getAbsolutePath() ) );
    	layer.setName( tgtLayerName );
    	
    	return layer;
	}
	
	public void setMultiLayerToolKit( MultiLayerThematicMapToolKit mltk ) {
		this.mltk =mltk;
	}
	
	public MultiLayerThematicMap openMultiLayerThematicMapFromArgument( String fileName, JFrameMultiLayerThematicMap jFrame  ) {
		MultiLayerThematicMap mltm =null;

		try {
			MultiLayerThematicMapDAO  thematicMapDAO = (MultiLayerThematicMapDAO)daof.get( DAOFactory.MULTI_LAYER_THEMATIC_MAP );
	    	mltm =(MultiLayerThematicMap)thematicMapDAO.load( fileName );
	    	jFrame.setMultiLayerThematicMap( mltm );

		} catch( Exception e ) {
			e.printStackTrace();
		}
    	
    	return mltm;
	}
	
	public ExcelMacroHelper generateThematicMapFromExcelMacro( String fileName ) {
		ExcelMacroHelper emh =null;
		
		try {
			
			emh =new ExcelMacroHelper();

			emh.generateThematicMapFromExcelMacro( fileName );
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return emh;
	}

}
